﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using fideeraSoft.Handlers;
using fideeraSoft.Utils;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Drawing;

namespace fideeraSoft.Paneles
{
    class RemitoPanelModificar:PanelGeneral
    {
        private System.Windows.Forms.Button btBuscarRemitoId;
        private System.Windows.Forms.DataGridView dgvMostrarRemitos;
        private System.Windows.Forms.Button btGuardarCambios;
        private System.Windows.Forms.Button btBuscarRemitoCod;
        private System.Windows.Forms.TableLayoutPanel tlpBotones;
        private System.Windows.Forms.TableLayoutPanel tlpBuscarRemitoCod;
        private System.Windows.Forms.TextBox tbBuscarRemitoId;
        private System.Windows.Forms.TextBox tbBuscarRemitoCod;
        private System.Windows.Forms.Button btVolver;
        private System.Windows.Forms.TableLayoutPanel tlpBuscarRemitoId;
        private DataSet changes;
        private SqlDataAdapter adapter;

        private DataSet ds;
        private SqlCommandBuilder cmdBuilder;

        int locationBuscarRemitoId=0;
        int locationBuscarRemitoCod = 0;

        public RemitoPanelModificar(Handler handler)
        {
            this.formatearPanelGeneral(handler);

            try
            {
                InitializeComponent();
                this.formatearTableTitulo("MODIFICACIÓN DE REMITO DE ENTRADA");

                string query = "SELECT re.ID AS [ID Remito de Entrada], re.codigo AS Código, re.fechaEntrada AS [Fecha de Remito de Entrada], us.username AS Usuario, pv.razonSocial AS Proveedor, re.fechaRecepcion AS [Fecha de Recepción] FROM RemitoEntrada AS re  INNER JOIN Usuario AS us ON us.ID=re.usuario INNER JOIN Proveedor AS pv ON pv.ID=re.proveedor";
                adapter = SQLclass.obtenerAdapter(query);
                if (adapter != null)
                {
                    ds = new DataSet();
                    adapter.Fill(ds);

                    
                    dgvMostrarRemitos.DataSource = ds.Tables[0];

                    if (ds.Tables[0].Rows.Count <= 0)
                        MessageBox.Show("NO HAY NINGUN REMITO DE ENTRADA CARGADO", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                    formatearDataGrid();

                    formatearTablaBuscarRemitoId();

                    formatearTablaBuscarRemitoCod();

                    formatearTablaBotones();


                    this.Controls.Add(dgvMostrarRemitos);
                    this.Controls.Add(tlpBuscarRemitoId);
                    this.Controls.Add(tlpBuscarRemitoCod);
                    this.Controls.Add(tlpBotones);

                    
                }

                else
                {
                    //CLogger.Append("[ProveedorPanelMostrar] Lista Proveedor mostrar Null: ", CLogger.INFO);      //DEBUG
                    MessageBox.Show("NO HAY NINGUN REMITO DE ENTRADA CARGADO", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    this.handler.backToPrincipal();
                }

            }
            catch (MiException ex)
            {

                CLogger.Append("[ProveedorPanelModificar] Exception: " + ex, CLogger.ERROR);      //DEBUG

            }    
        }

        #region Formato 
        private void formatearDataGrid()
        {
            dgvMostrarRemitos.AutoGenerateColumns = true;
            dgvMostrarRemitos.Size = new Size(this.Size.Width - 100, this.Size.Height - 400);
            dgvMostrarRemitos.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.Fill);
            dgvMostrarRemitos.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllHeaders);
            dgvMostrarRemitos.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            dgvMostrarRemitos.BorderStyle = BorderStyle.Fixed3D;

            dgvMostrarRemitos.Location = new Point(MetodosGenerales.calcularCenterWidth(this.Size.Width, dgvMostrarRemitos.Size.Width), this.InitialRealPointVertical);
        }

        private void formatearTablaBuscarRemitoId()
        {
            tlpBuscarRemitoId.Controls.Add(btBuscarRemitoId);
            tlpBuscarRemitoId.Controls.Add(tbBuscarRemitoId);
                        
            int wid = MetodosGenerales.calcularCenterWidth(handler.FormFrame.Size.Width, tlpBuscarRemitoId.Size.Width);

            locationBuscarRemitoId = this.InitialRealPointVertical + dgvMostrarRemitos.Size.Height + 15;

            tlpBuscarRemitoId.Location = new Point(wid, locationBuscarRemitoId);


        }

        private void formatearTablaBuscarRemitoCod()
        {
            

            locationBuscarRemitoCod = locationBuscarRemitoId + tlpBuscarRemitoId.Size.Height;

            tlpBuscarRemitoCod.Location = new Point(MetodosGenerales.calcularCenterWidth(this.Size.Width, tlpBuscarRemitoCod.Size.Width), locationBuscarRemitoCod);

            tlpBuscarRemitoCod.Controls.Add(btBuscarRemitoCod);
            tlpBuscarRemitoCod.Controls.Add(tbBuscarRemitoCod);


        }

        private void formatearTablaBotones()
        {
            int locationBtCambios = locationBuscarRemitoCod + tlpBuscarRemitoCod.Size.Height + 10;
            tlpBotones.Location = new Point(MetodosGenerales.calcularCenterWidth(this.handler.FormFrame.Size.Width, tlpBotones.Size.Width), locationBtCambios);

            tlpBotones.Controls.Add(btVolver);
            tlpBotones.Controls.Add(btGuardarCambios);

        }
        
        #endregion

        #region INICIALIZAR COMPONENTES
        private void InitializeComponent()
        {
            this.btBuscarRemitoId = new System.Windows.Forms.Button();
            this.dgvMostrarRemitos = new System.Windows.Forms.DataGridView();
            this.btGuardarCambios = new System.Windows.Forms.Button();
            this.btBuscarRemitoCod = new System.Windows.Forms.Button();
            this.tlpBotones = new System.Windows.Forms.TableLayoutPanel();
            this.tlpBuscarRemitoCod = new System.Windows.Forms.TableLayoutPanel();
            this.tbBuscarRemitoId = new System.Windows.Forms.TextBox();
            this.tbBuscarRemitoCod = new System.Windows.Forms.TextBox();
            this.btVolver = new System.Windows.Forms.Button();
            this.tlpBuscarRemitoId = new System.Windows.Forms.TableLayoutPanel();
            ((System.ComponentModel.ISupportInitialize)(this.dgvMostrarRemitos)).BeginInit();
            this.SuspendLayout();
            // 
            // btBuscarRemitoId
            // 
            this.btBuscarRemitoId.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.btBuscarRemitoId.BackColor = System.Drawing.Color.AliceBlue;
            this.btBuscarRemitoId.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btBuscarRemitoId.Font = new System.Drawing.Font("Bodoni MT", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btBuscarRemitoId.Location = new System.Drawing.Point(0, 0);
            this.btBuscarRemitoId.Name = "btBuscarRemitoId";
            this.btBuscarRemitoId.Size = new System.Drawing.Size(75, 23);
            this.btBuscarRemitoId.TabIndex = 0;
            this.btBuscarRemitoId.Text = "Buscar Remito (ID)";
            this.btBuscarRemitoId.UseVisualStyleBackColor = false;
            this.btBuscarRemitoId.Click += new System.EventHandler(this.btBuscarRemitoId_Click);
            // 
            // dgvMostrarRemitos
            // 
            this.dgvMostrarRemitos.AllowUserToResizeRows = false;
            this.dgvMostrarRemitos.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.dgvMostrarRemitos.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgvMostrarRemitos.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnF2;
            this.dgvMostrarRemitos.Location = new System.Drawing.Point(0, 0);
            this.dgvMostrarRemitos.Name = "dgvMostrarRemitos";
            this.dgvMostrarRemitos.RowTemplate.DefaultCellStyle.Font = new System.Drawing.Font("Bodoni MT", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dgvMostrarRemitos.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect;
            this.dgvMostrarRemitos.Size = new System.Drawing.Size(240, 150);
            this.dgvMostrarRemitos.TabIndex = 0;
            this.dgvMostrarRemitos.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvMostrarRemitos_CellClick);
            this.dgvMostrarRemitos.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvMostrarRemitos_CellContentClick);
            // 
            // btGuardarCambios
            // 
            this.btGuardarCambios.BackColor = System.Drawing.Color.AliceBlue;
            this.btGuardarCambios.Font = new System.Drawing.Font("Bodoni MT", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btGuardarCambios.Location = new System.Drawing.Point(0, 0);
            this.btGuardarCambios.Margin = new System.Windows.Forms.Padding(12, 3, 3, 3);
            this.btGuardarCambios.Name = "btGuardarCambios";
            this.btGuardarCambios.Size = new System.Drawing.Size(75, 40);
            this.btGuardarCambios.TabIndex = 0;
            this.btGuardarCambios.Text = "Guardar";
            this.btGuardarCambios.UseVisualStyleBackColor = false;
            this.btGuardarCambios.Click += new System.EventHandler(this.btGuardarCambios_Click);
            // 
            // btBuscarRemitoCod
            // 
            this.btBuscarRemitoCod.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.btBuscarRemitoCod.BackColor = System.Drawing.Color.AliceBlue;
            this.btBuscarRemitoCod.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btBuscarRemitoCod.Font = new System.Drawing.Font("Bodoni MT", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btBuscarRemitoCod.Location = new System.Drawing.Point(0, 0);
            this.btBuscarRemitoCod.Name = "btBuscarRemitoCod";
            this.btBuscarRemitoCod.Size = new System.Drawing.Size(75, 23);
            this.btBuscarRemitoCod.TabIndex = 0;
            this.btBuscarRemitoCod.Text = "Buscar Remito (Código)";
            this.btBuscarRemitoCod.UseVisualStyleBackColor = false;
            this.btBuscarRemitoCod.Click += new System.EventHandler(this.btBuscarRemitoCod_Click);
            // 
            // tlpBotones
            // 
            this.tlpBotones.BackColor = System.Drawing.Color.LightCyan;
            this.tlpBotones.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single;
            this.tlpBotones.ColumnCount = 2;
            this.tlpBotones.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBotones.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBotones.Location = new System.Drawing.Point(0, 0);
            this.tlpBotones.Name = "tlpBotones";
            this.tlpBotones.RowCount = 1;
            this.tlpBotones.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBotones.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBotones.Size = new System.Drawing.Size(200, 46);
            this.tlpBotones.TabIndex = 0;
            // 
            // tlpBuscarRemitoCod
            // 
            this.tlpBuscarRemitoCod.BackColor = System.Drawing.Color.LightCyan;
            this.tlpBuscarRemitoCod.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single;
            this.tlpBuscarRemitoCod.ColumnCount = 2;
            this.tlpBuscarRemitoCod.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoCod.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoCod.Location = new System.Drawing.Point(0, 0);
            this.tlpBuscarRemitoCod.Name = "tlpBuscarRemitoCod";
            this.tlpBuscarRemitoCod.RowCount = 1;
            this.tlpBuscarRemitoCod.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoCod.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoCod.Size = new System.Drawing.Size(400, 40);
            this.tlpBuscarRemitoCod.TabIndex = 0;
            // 
            // tbBuscarRemitoId
            // 
            this.tbBuscarRemitoId.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
            this.tbBuscarRemitoId.Font = new System.Drawing.Font("Bodoni MT", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.tbBuscarRemitoId.Location = new System.Drawing.Point(0, 0);
            this.tbBuscarRemitoId.MaxLength = 8;
            this.tbBuscarRemitoId.Name = "tbBuscarRemitoId";
            this.tbBuscarRemitoId.Size = new System.Drawing.Size(100, 30);
            this.tbBuscarRemitoId.TabIndex = 0;
            // 
            // tbBuscarRemitoCod
            // 
            this.tbBuscarRemitoCod.Font = new System.Drawing.Font("Bodoni MT", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.tbBuscarRemitoCod.Location = new System.Drawing.Point(0, 0);
            this.tbBuscarRemitoCod.MaxLength = 10;
            this.tbBuscarRemitoCod.Name = "tbBuscarRemitoCod";
            this.tbBuscarRemitoCod.Size = new System.Drawing.Size(140, 30);
            this.tbBuscarRemitoCod.TabIndex = 0;
            // 
            // btVolver
            // 
            this.btVolver.BackColor = System.Drawing.Color.AliceBlue;
            this.btVolver.Font = new System.Drawing.Font("Bodoni MT", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btVolver.Location = new System.Drawing.Point(0, 0);
            this.btVolver.Margin = new System.Windows.Forms.Padding(12, 3, 3, 3);
            this.btVolver.Name = "btVolver";
            this.btVolver.Size = new System.Drawing.Size(75, 40);
            this.btVolver.TabIndex = 0;
            this.btVolver.Text = "Volver";
            this.btVolver.UseVisualStyleBackColor = false;
            this.btVolver.Click += new System.EventHandler(this.btVolver_Click);
            // 
            // tlpBuscarRemitoId
            // 
            this.tlpBuscarRemitoId.BackColor = System.Drawing.Color.LightCyan;
            this.tlpBuscarRemitoId.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single;
            this.tlpBuscarRemitoId.ColumnCount = 2;
            this.tlpBuscarRemitoId.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoId.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoId.Location = new System.Drawing.Point(0, 0);
            this.tlpBuscarRemitoId.Name = "tlpBuscarRemitoId";
            this.tlpBuscarRemitoId.RowCount = 1;
            this.tlpBuscarRemitoId.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoId.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoId.Size = new System.Drawing.Size(400, 40);
            this.tlpBuscarRemitoId.TabIndex = 0;
            ((System.ComponentModel.ISupportInitialize)(this.dgvMostrarRemitos)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion


        private void btBuscarRemitoId_Click(object sender, EventArgs e)
        {
            if (dgvMostrarRemitos.CurrentCell == null)
            {
                MessageBox.Show("NO HAY DATOS EN LA TABLA", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            dgvMostrarRemitos.ClearSelection();
            if (!string.IsNullOrWhiteSpace(tbBuscarRemitoId.Text) )
            {
                string searchValue = tbBuscarRemitoId.Text;
                int inRowFinded = -1;

                try
                {
                    foreach (DataGridViewRow row in dgvMostrarRemitos.Rows)
                    {
                        if (row.Cells[0].Value.ToString().Equals(searchValue))
                        {
                            dgvMostrarRemitos.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                            row.Selected = true;
                            inRowFinded = row.Index;
                            //   MessageBox.Show("ENCONTRE: " + inRowFinded, "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            dgvMostrarRemitos.CurrentCell = row.Cells[0];
                            tbBuscarRemitoId.Clear();

                            break;
                        }
                    }

                }
                catch (Exception exc)
                {
                    //MessageBox.Show(exc.Message);     //DEBUG
                    //CLogger.Append("[btBuscarProvCuil_Click] Exception: " + exc, CLogger.ERROR);      //DEBUG
                    tbBuscarRemitoId.Clear();
                    MessageBox.Show("NO SE ENCONTRO EL REMITO", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            else
            {
                MessageBox.Show("NO SE INGRESO NINGÚN NUMERO DE ID", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            }
        }

        private void btBuscarRemitoCod_Click(object sender, EventArgs e)
        {
            if (dgvMostrarRemitos.CurrentCell == null)
            {
                MessageBox.Show("NO HAY DATOS EN LA TABLA", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            dgvMostrarRemitos.ClearSelection();
            if (!string.IsNullOrWhiteSpace(tbBuscarRemitoCod.Text))
            {
                string searchValue = tbBuscarRemitoCod.Text;
                int inRowFinded = -1;
                try
                {
                    foreach (DataGridViewRow row in dgvMostrarRemitos.Rows)
                    {
                        if (row.Cells[1].Value.ToString().Equals(searchValue))
                        {
                            dgvMostrarRemitos.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

                            row.Selected = true;

                            inRowFinded = row.Index;
                            //MessageBox.Show("ENCONTRE: "+inRowFinded, "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            dgvMostrarRemitos.CurrentCell = row.Cells[0];
                            tbBuscarRemitoCod.Clear();
                            break;

                        }
                    }
                }
                catch (Exception exc)
                {
                    tbBuscarRemitoCod.Clear();
                    //MessageBox.Show(exc.Message); //DEBUG
                    //CLogger.Append("[btBuscarProvRaz_Click] Exception: " + exc, CLogger.ERROR);      //DEBUG
                    MessageBox.Show("NO SE ENCONTRO EL REMITO", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            else
            {
                MessageBox.Show("NO SE INGRESO CÓDIGO REMITO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            }
        }

        private void btVolver_Click(object sender, EventArgs e)
        {
            this.handler.backToPrincipal();
        }

        private void btGuardarCambios_Click(object sender, EventArgs e)
        {
            try
            {
                if (adapter != null)
                {
                    cmdBuilder = new SqlCommandBuilder(adapter);
                    changes = ds.GetChanges();
                    if (changes != null)
                    {
                        adapter.Update(changes);
                        MessageBox.Show("CAMBIOS GUARDADOS", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    else
                    {
                        MessageBox.Show("NO HAY CAMBIOS EN LA TABLA", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }

                }
            }
            catch (Exception exc)
            {
                MessageBox.Show("ERROR AL GUARDAR LOS DATOS.\nNo se guardaran los datos. \nVerifique celtas modificadas y cantidad de dígitos modificados.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                CLogger.Append("[btGuardarCambios_Click] Exception: " + exc, CLogger.ERROR);      //DEBUG
                this.handler.backToPrincipal();
            }
        }

        private void dgvMostrarRemitos_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show("CANT COLUMNS: " + dgvMostrarRemitos.Columns.Count, "INFO", MessageBoxButtons.OK, MessageBoxIcon.Error);
            
            //dgvMostrarRemitos.SelectionMode = DataGridViewSelectionMode.CellSelect;
        }

        private void dgvMostrarRemitos_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvMostrarRemitos.Columns.Count > 0)
            {
                dgvMostrarRemitos.Columns[3].ReadOnly = true;
                dgvMostrarRemitos.Columns[4].ReadOnly = true;
            }

            dgvMostrarRemitos.SelectionMode = DataGridViewSelectionMode.CellSelect;
        }
    }
}
